//
//  CZUserAccountViewModel.swift
//  01-sinaWeibo-05-09
//
//  Created by mac on 16/5/14.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {
    
    //单例
    static let sharedInstance:CZUserAccountViewModel = CZUserAccountViewModel()
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!+"/account.plist"
    
    //账号全局只要拿到单例就可以访问
    var userAccount:CZUserAccount?
    //用户是否登录成功
    var isUserLogin:Bool {
        get
        {
            return userAccount != nil //账号!= nil就表示登录了
        }
    }
    override init() {
        super.init()
        // 单例创建的时候就会加载沙盒里面的账号,赋值给userAccount, 只需要加载一次
        userAccount = loadUserAccount()
    }

    // 发送POST请求获取AccessToken
    func loadAccessToken(code: String,callback:(error: NSError?)->()) {

    
    // 如果urlString里面开头是http或https就直接使用这个urlString,如果不是以http或https开头AFN会帮我们拼接baseURL
    let urlString = "oauth2/access_token"
    
    // 参数
    let parameters = [
        "client_id" : client_id,
        "client_secret" : client_secret,
        "grant_type" : "authorization_code",
        "code" : code,
        "redirect_uri": redirect_uri
    ]
    
    
    
    // 发送POST请求获取AccessToken
    // 如果已经授权成功消息在授权的时候不会再看到这个界面,相当于新浪会自动帮我们点击授权按钮,
    // 如果还想自己来收取需要去网站上面取消授权
    // ((NSURLSessionDataTask, AnyObject?) -> Void)?
    CZNetworkTool.sharedInstance.request(RequestMethod.POST, URLSTring: urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
    CZPrint(items: "获取成功:\(responseObject)")
    //                    SVProgressHUD.showSuccessWithStatus("授权成功")
    //                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
    //                        self.close()
    //                    })
    
    
    if let result = responseObject as? [String : AnyObject]
    {
    let userAccount = CZUserAccount(dic: result)
    CZPrint(items: "userAccount:\(userAccount)")

    CZPrint(items: "userAccoutPath:\(self.userAccountPath)")
        
        
    NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
        self.userAccount = userAccount
        
        // 调用归档的方法,将模型归档到沙盒里面
        // 让userAccount对象保存到self.userAccountPath这个路径
        self.saveUserAccount()
        //告诉控制器,模型保存完成
        callback(error: nil)
        
    }else
    {
    CZPrint(items: "返回数据转字典失败")
    }

    }, failure: { (task, error) -> Void in
    CZPrint(items: "获取失败:\(error)")
        callback(error: error)
    
    })
  }
    //保存账号在沙盒里
    private func saveUserAccount(){
    
        //调用归档方法,将模型保存在沙盒里面
        if let account = userAccount {
        
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        }
    }
    
    //解档账号
    func loadUserAccount()->CZUserAccount?
    {
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount
        {
            // 加载到了账号, 判断是否过期
            // userAccount.expiresDate 和当前时间比较
            // NSDate(): 当前时间
            // userAccount.expiresDate < NSDate() 过期的
            // 测试:1.改系统时间 2.改userAccount.expiresDate属性,早期的时间
            //            userAccount.expiresDate = NSDate(timeIntervalSinceNow: -1000)

            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending
            {
            
                CZPrint(items: "没有过期")
                return userAccount
            }else
                {
                    return nil
                }
        }else
        {
            return nil
        }
        
    }
    //MARK:-获取用户名称和头像
    //加载用户信息 用户名称和头像
    func laodUserInfo(laodUserInfoCallback:()->()){
    
        guard let access_token = userAccount?.access_token else
        {
            CZPrint(items: "access_token没值")
            return
        }
        guard let uid = userAccount?.uid else{
        
            CZPrint(items: "uid没有值")
            return
        }
        
        let urlstring = "2/users/show.json"
        //参数
        let parameters =
        [
            "access_token": access_token,
            "uid": uid
        ]
        
        //发送请求
        CZNetworkTool.sharedInstance.request(RequestMethod.GET, URLSTring: urlstring, parameters: parameters, progress: nil , success: { (_, responseObject) -> Void in
            
//             CZPrint(items: "获取用户信息: \(responseObject)")
            if let result = responseObject as? [String : AnyObject]{
            
                //只需要获取用户的名称和头像
                let screen_name = result["screen_name"] as? String
                
                let avatar_large = result["avatar_large"] as? String
                
                //赋值到当前账号的模型中
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                //将userAccount保存在沙盒里面
                self.saveUserAccount()
            }
            
            
            }) { (_, error) -> Void in
                CZPrint(items: "获取用户信息出错了: \(error)")
        }
        
    }
}
